<script setup lang="tsx">
import { ref, inject, computed, onMounted } from 'vue';
import MyTable from '@/components/myTable/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { Space, Link } from 'tdesign-vue-next';
import { SearchIcon } from 'tdesign-icons-vue-next';
// import { getList } from '@/api/task/financial';
import { list } from '@/api/statistics/teamStatistics/teamStatistics';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const typeList = ref([]);
onMounted(() => {
  onReset();
});

const columns = [
  { title: '会员账号', colKey: 'username' },
  { title: '锁定团队', colKey: 'locked' },
  { title: '团队人数', colKey: 'teamCount' },
  { title: '直推人员数量', colKey: 'directCount' },
  { title: '新增会员', colKey: 'purchaseMemberCount' },
  { title: '充值', colKey: 'rechargeAmount' },
  { title: '提现', colKey: 'withdrawAmount' },
  { title: '下级任务返点', colKey: 'subordinateTaskPoints' },
  { title: '活动', colKey: 'activityAmount' },
  { title: '购买会员', colKey: 'purchaseMember' },
  { title: '推广奖励', colKey: 'promotionReward' },
  { title: '任务佣金', colKey: 'taskCommission' },
  { title: '其他', colKey: 'otherAmount' },
  { title: '操作', colKey: 'op' },
];

const footData = computed(() => {
  const rechargeTotal = data.value.reduce((sum, item) => sum + (Number(item.rechargeAmount) || 0), 0);

  return [
    {
      username: '分页合计',
      rechargeAmount: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(rechargeTotal),
      // 你可以按需添加其它字段的合计
    },
  ];
});

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  username: string | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  username: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
const balanceRange = ref<[number | null, number | null]>([null, null]);
const render = () => (
  <>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.username} placeholder="账号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      {/* <t-date-range-picker v-model={dateRange.value} placeholder="时间" /> */}
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="uid"
      onUnGetList={unGetList}
      footData={footData.value}
    >
      {{
        
        locked: (slotProps: any) => (
          <t-switch
            size="large"
            theme={slotProps.row.locked === 1 ? 'danger' : 'primary'}
            onClick={() => {
              
              slotProps.row.locked = slotProps.row.locked === 1 ? 0 : 1;
           
            }}
          >
            {slotProps.row.locked === 1 ? '已锁定' : '未锁定'}
          </t-switch>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => getChild(slotProps)}>
              上级
            </Link>
            <Link theme="primary" onClick={() => getChild(slotProps)}>
              下级
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await list({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};
unGetList();

/**
 * 获取全部团队报表数据（自动翻页）
 */
const fetchAllTeamReport = async () => {
  let pageNum = 1;
  const pageSize = 10; // 可根据实际情况调整
  let allRows: any[] = [];
  let total = 0;

  while (true) {
    const res = await list({
      ...addDateRange?.(queryForm.value, dateRange.value),
      pageNum,
      pageSize,
    });
    if (res?.rows?.length) {
      allRows = allRows.concat(res.rows);
      total = res.total;
      pageNum++;
    } else {
      break;
    }
  }

  return {
    rows: allRows,
    total,
  };
};

const downloadReport = async () => {
  // const { t } = useI18n();
  const params = {
    ...addDateRange?.(queryForm.value, dateRange.value),
  };
  try {
    // const res = await downloadFile({ ...params });
    // const url = window.URL.createObjectURL(new Blob([res]));
    // const link = document.createElement('a');
    // link.href = url;
    // link.setAttribute('download', '团队报表.xlsx'); // or any other extension
    // document.body.appendChild(link);
    // link.click();
    // document.body.removeChild(link);
    // this.$message.success(t('common.downloadSuccess'));
  } catch (error) {
    console.error('下载失败', error);
    // this.$message.error(t('common.downloadFail'));
  }
};

// 获取类型

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  balanceRange.value = [null, null];
  dateRange.value = [];
  unGetList();
  console.log('重置查询条件');
};

// 下级
const getChild = async (slotProps: any) => {};

const getName = (lid: any, id: any, list: any, name: any) => {
  if (!id) return '';
  return list.find((item: { [x: string]: any }) => item[lid] == id)[name];
};


</script>

<template>
  <div>
    <render />
  </div>
</template>
